package org.leon.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.leon.service.UserService;
import org.leon.service.UserServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/4/18.
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Resource
    private UserService userService;

    private static List<User> userlist;

    public UserController(){
        userlist = new ArrayList<>();
    }

    private static final Log logger = LogFactory.getLog(UserController.class);



    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String registerForm(){
        logger.info("registerForm is called. GET");
        // register page
        return "registerForm";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(
            @RequestParam("loginname") String loginname,
            @RequestParam("password") String password,
            @RequestParam("username") String username
    ){
        logger.info("register is called. POST");
        User u = new User();
        u.setLoginname(loginname);
        u.setPassword(password);
        u.setUsername(username);
        userlist.add(u);
        // to login page
        return "loginForm";
    }

    @RequestMapping(value = "/login")
    public String login(
            @RequestParam("loginname") String loginname,
            @RequestParam("password") String password,
            Model model
    ){
        logger.info("login is called.");
        logger.info("loginname: "+loginname+", password: "+password);
        for (User user: userlist
             ) {
            if(user.getLoginname().equals(loginname)
                    && user.getPassword().equals(password)){
                model.addAttribute("user",user);
                return "welcome";
            }
        }
        return "loginForm";
    }
    @RequestMapping(value = "/logout", method = RequestMethod.GET, produces = "application/json")
    public String logout(){
        return "logout";
    }

    /**
     * Test SpringMVC & MyBaits
     * @return
     */
    @RequestMapping(value = "/findAllUser")
    public String findAllUser(){
        List<org.leon.mybatis.domain.User> all = userService.findAll();
        System.out.println(all);

        return "welcome";

    }

}
